package com.example.blockbreaker;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.HapticFeedbackConstants;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.slider.Slider;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;


// CravingFragment.java
public class CravingFragment extends Fragment {
    private static final int BREATHING_REQUEST_CODE = 1001; // 可以是任意唯一整数
    private MaterialButton btnBreathing;
    private SharedPreferences prefs;

    private MaterialButton btnDistraction;
    private Random random = new Random();

    private MaterialButton btnSaveCraving;
    private Slider sliderCravingLevel;
    private TextInputEditText etTrigger;

    private MaterialButton btnSave;
    private CravingViewModel viewModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_craving, container, false);

        // 初始化组件
        btnBreathing = view.findViewById(R.id.btn_breathing);
        prefs = requireActivity().getSharedPreferences("QuitSmokePrefs", Context.MODE_PRIVATE);

        // 初始化组件
        btnDistraction = view.findViewById(R.id.btn_distraction);
        prefs = requireActivity().getSharedPreferences("QuitSmokePrefs", Context.MODE_PRIVATE);

        setupDistractionButton();
        setupBreathingButton();

        // 初始化视图
        btnSave = view.findViewById(R.id.btn_save_craving);
        sliderCravingLevel = view.findViewById(R.id.slider_craving_level);
        etTrigger = view.findViewById(R.id.et_trigger);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(CravingViewModel.class);

        setupSaveButton();

        return view;
    }

    private void setupSaveButton() {
        btnSave.setOnClickListener(v -> {
            // 1. 触觉反馈
            provideHapticFeedback();

            // 2. 收集数据
            CravingRecord record = createCravingRecord();
            if (record == null) return; // 验证失败

            // 3. 保存数据
            saveCravingRecord(record);

            // 4. 用户反馈
            showSaveConfirmation(record);

            // 5. 重置表单
            resetForm();
        });
    }

    private void provideHapticFeedback() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            btnSave.performHapticFeedback(HapticFeedbackConstants.CONFIRM);
        } else {
            btnSave.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
        }
    }

    private CravingRecord createCravingRecord() {
        // 获取输入值
        int cravingLevel = (int) sliderCravingLevel.getValue();
        String trigger = etTrigger.getText().toString().trim();
        long timestamp = System.currentTimeMillis();

        // 验证数据
        if (cravingLevel < 1 || cravingLevel > 10) {
            showError("请选择有效的烟瘾等级(1-10)");
            return null;
        }

        return new CravingRecord(cravingLevel, trigger, timestamp);
    }

    private void saveCravingRecord(CravingRecord record) {
        // 通过ViewModel保存
        viewModel.insertRecord(record);

        // 可选：本地存储最新记录
        SharedPreferences prefs = requireActivity().getSharedPreferences("CravingPrefs", Context.MODE_PRIVATE);
        prefs.edit()
                .putInt("last_craving_level", record.getLevel())
                .putString("last_craving_trigger", record.getTrigger())
                .apply();
    }

    private void showSaveConfirmation(CravingRecord record) {
        String message = "记录已保存！";

        // 根据烟瘾强度提供建议
        if (record.getLevel() >= 8) {
            message += "\n检测到高强度烟瘾，建议立即进行呼吸练习";
        } else if (record.getLevel() >= 5) {
            message += "\n您做得很好，继续保持！";
        }

        // 使用Snackbar显示
        Snackbar snackbar = Snackbar.make(
                requireView(),
                message,
                Snackbar.LENGTH_LONG
        );

        // 为高强度烟瘾添加快速操作
        if (record.getLevel() >= 7) {
            snackbar.setAction("开始练习", v -> {
                startActivity(new Intent(requireActivity(), BreathingActivity.class));
            });
        }

        snackbar.show();
    }

    private void resetForm() {
        // 重置滑块到中间值
        sliderCravingLevel.setValue(5f);

        // 清空输入
        etTrigger.setText("");
        etTrigger.clearFocus();

        // 隐藏键盘
        InputMethodManager imm = (InputMethodManager) requireActivity()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etTrigger.getWindowToken(), 0);
    }

    private void showError(String message) {
        Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT).show();
    }
    private boolean validateInput() {
        // 确保至少选择了渴望强度
        if (sliderCravingLevel.getValue() < 1) {
            Snackbar.make(requireView(),
                    "请选择烟瘾强度等级",
                    Snackbar.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void saveCravingRecord(int level, String trigger, long timestamp) {
        // 创建记录对象
        CravingRecord record = new CravingRecord(level, trigger, timestamp);

        // 获取SharedPreferences编辑器
        SharedPreferences.Editor editor = prefs.edit();

        // 保存最新记录
        editor.putInt("last_craving_level", level);
        editor.putString("last_craving_trigger", trigger);
        editor.putLong("last_craving_time", timestamp);

        // 更新统计数据
        int totalRecords = prefs.getInt("total_craving_records", 0) + 1;
        editor.putInt("total_craving_records", totalRecords);

        // 计算平均强度
        int totalLevel = prefs.getInt("total_craving_level", 0) + level;
        editor.putInt("total_craving_level", totalLevel);
        editor.putFloat("avg_craving_level", totalLevel / (float) totalRecords);

        editor.apply();

        // 保存到数据库(可选)
        saveToDatabase(record);
    }

    private void saveToDatabase(CravingRecord record) {
        // 使用ViewModel和LiveData异步保存
        CravingViewModel viewModel = new ViewModelProvider(this).get(CravingViewModel.class);
        viewModel.insertRecord(record);
    }
// CravingViewModel.java

    static public class CravingViewModel extends AndroidViewModel {
        private final CravingRepository repository;
        private final Executor executor = Executors.newSingleThreadExecutor();
        private final MutableLiveData<Boolean> isLoading = new MutableLiveData<>(false);
        private final MutableLiveData<String> errorMessage = new MutableLiveData<>();

        public CravingViewModel(@NonNull Application application) {
            super(application);
            repository = new CravingRepository(application);
        }

        // ================= 核心操作 =================
        public void insertRecord(CravingRecord record) {
            isLoading.postValue(true);
            executor.execute(() -> {
                try {
                    repository.insertRecord(record);
                } catch (Exception e) {
                    errorMessage.postValue("保存失败: " + e.getMessage());
                } finally {
                    isLoading.postValue(false);
                }
            });
        }

        public void deleteRecord(CravingRecord record) {
            executor.execute(() -> repository.deleteRecord(record));
        }

        // ================= 查询方法 =================
        public LiveData<List<CravingRecord>> getAllRecords() {
            return repository.getAllRecords();
        }

        public LiveData<List<CravingRecord>> getRecentRecords(int days) {
            long timestamp = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000L);
            return repository.getRecordsAfter(timestamp);
        }


        // ================= 实用方法 =================
        public LiveData<Integer> getTodayCravingCount() {
            long startOfDay = getStartOfDayTimestamp();
            return repository.getCountBetween(startOfDay, System.currentTimeMillis());
        }

        public LiveData<Float> getAverageLevelLastWeek() {
            long oneWeekAgo = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000L);
            return repository.getAverageLevelSince(oneWeekAgo);        }

        // ================= 状态监听 =================
        public LiveData<Boolean> getIsLoading() {
            return isLoading;
        }

        public LiveData<String> getErrorMessage() {
            return errorMessage;
        }

        private long getStartOfDayTimestamp() {
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            return calendar.getTimeInMillis();
        }
    }
    private void showSaveConfirmation(int level) {
        String message;
        if (level >= 8) {
            message = "记录已保存！这个烟瘾很强，你做得很棒！";
        } else if (level >= 5) {
            message = "记录已保存！继续保持！";
        } else {
            message = "记录已保存！";
        }

        // 使用Snackbar显示反馈
        Snackbar snackbar = Snackbar.make(
                requireView(),
                message,
                Snackbar.LENGTH_LONG);

        // 为高强度烟瘾添加额外帮助选项
        if (level >= 7) {
            snackbar.setAction("获取帮助", v -> {
                showDistractionActivity();
            });
        }

        snackbar.show();
    }
    private void setupDistractionButton() {
        btnDistraction.setOnClickListener(v -> {
            // 1. 提供触觉反馈
            provideHapticFeedback();

            // 2. 记录按钮点击事件
            recordDistractionRequest();

            // 3. 显示分散注意力活动建议
            showDistractionActivity();
        });
    }

    private void recordDistractionRequest() {
        int distractionRequests = prefs.getInt("distraction_requests", 0) + 1;
        prefs.edit()
                .putInt("distraction_requests", distractionRequests)
                .putLong("last_distraction_time", System.currentTimeMillis())
                .apply();
    }

    private void showDistractionActivity() {
        // 获取适合当前场景的活动建议
        String activity = getContextualDistractionActivity();
        String motivationalQuote = CravingHelper.getRandomMotivationalQuote();

        // 创建自定义对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext(), R.style.CustomAlertDialog);
        builder.setTitle("试试这个活动:");

        // 自定义对话框布局
        View dialogView = LayoutInflater.from(requireContext())
                .inflate(R.layout.dialog_distraction, null);

        TextView tvActivity = dialogView.findViewById(R.id.tv_activity);
        TextView tvQuote = dialogView.findViewById(R.id.tv_quote);
        ImageView ivIcon = dialogView.findViewById(R.id.iv_icon);

        tvActivity.setText(activity);
        tvQuote.setText(motivationalQuote);
        ivIcon.setImageResource(getActivityIcon(activity));

        builder.setView(dialogView);

        // 设置按钮
        builder.setPositiveButton("开始活动", (dialog, which) -> {
            logActivityStarted(activity);
            startSelectedActivity(activity);
        });

        builder.setNegativeButton("换一个", (dialog, which) -> showDistractionActivity());

        builder.setNeutralButton("稍后", null);

        // 显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();

        // 自定义按钮颜色
        Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        positiveButton.setTextColor(ContextCompat.getColor(requireContext(), R.color.colorPrimary));
    }

    private String getContextualDistractionActivity() {
        // 根据一天中的时间、位置等提供上下文相关的建议
        int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        boolean isAtHome = prefs.getBoolean("is_at_home", true);
        int cravingLevel = prefs.getInt("last_craving_intensity", 3);

        String[] homeActivities = getResources().getStringArray(R.array.home_distraction_activities);
        String[] outdoorActivities = getResources().getStringArray(R.array.outdoor_distraction_activities);
        String[] highIntensityActivities = getResources().getStringArray(R.array.high_intensity_distractions);

        if (cravingLevel > 7) {
            return highIntensityActivities[random.nextInt(highIntensityActivities.length)];
        }

        return isAtHome ?
                homeActivities[random.nextInt(homeActivities.length)] :
                outdoorActivities[random.nextInt(outdoorActivities.length)];
    }

    private int getActivityIcon(String activity) {
        // 根据活动类型返回对应图标
        if (activity.contains("喝水")) return R.drawable.ic_water;
        if (activity.contains("散步")) return R.drawable.ic_walk;
        if (activity.contains("刷牙")) return R.drawable.ic_toothbrush;
        if (activity.contains("朋友")) return R.drawable.ic_friend;
        return R.drawable.ic_activity_default;
    }

    private void logActivityStarted(String activity) {
        // 记录用户选择的活动
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("last_distraction_activity", activity);
        editor.putLong("last_distraction_start_time", System.currentTimeMillis());
        editor.apply();
    }

    private void startSelectedActivity(String activity) {
        // 根据选择的活动类型执行相应操作
        if (activity.contains("喝水")) {
            Toast.makeText(requireContext(), "记得小口慢饮", Toast.LENGTH_SHORT).show();
        } else if (activity.contains("散步")) {
            openStepCounterApp();
        } else if (activity.contains("朋友")) {
            openContactsApp();
        }
        // 其他活动不需要特殊处理
    }

    private void openStepCounterApp() {
        try {
            Intent intent = new Intent("com.google.android.apps.fitness.VIEW_STEP_COUNT");
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(requireContext(),
                    "未找到计步应用，请尝试其他活动", Toast.LENGTH_SHORT).show();
        }
    }

    private void openContactsApp() {
        Intent intent = new Intent(Intent.ACTION_VIEW, ContactsContract.Contacts.CONTENT_URI);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(requireContext(),
                    "未找到通讯录应用", Toast.LENGTH_SHORT).show();
        }
    }


    private void setupBreathingButton() {
        btnBreathing.setOnClickListener(v -> {
            // 1. 记录按钮点击事件
            recordBreathingButtonClick();

            // 2. 启动呼吸练习Activity
            startBreathingActivity();

            // 3. 提供触觉反馈
            provideHapticFeedback();
        });
    }

    private void recordBreathingButtonClick() {
        // 记录呼吸练习请求次数
        int breathingRequests = prefs.getInt("breathing_requests", 0) + 1;
        prefs.edit().putInt("breathing_requests", breathingRequests).apply();

        // 记录最后一次请求时间
        prefs.edit().putLong("last_breathing_request", System.currentTimeMillis()).apply();

        Log.d("CravingHelp", "用户请求呼吸练习，总次数: " + breathingRequests);
    }

    private void startBreathingActivity() {
        // 创建显式Intent
        Intent intent = new Intent(getActivity(), BreathingActivity.class);

        // 可以传递额外参数
        intent.putExtra("source", "craving_fragment");
        intent.putExtra("craving_intensity",
                prefs.getInt("last_craving_intensity", 3));

        // 启动Activity并添加过渡动画
        startActivity(intent);
    }


    // 可选：监听呼吸练习完成结果
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BREATHING_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            showExerciseCompletionMessage();
        }
    }

    private void showExerciseCompletionMessage() {
        long duration = prefs.getLong("last_breathing_duration", 0);
        String message = duration > 0 ?
                String.format("你完成了%d秒呼吸练习！", duration / 1000) :
                "呼吸练习已完成！";

        Snackbar.make(requireView(), message, Snackbar.LENGTH_LONG)
                .setAction("查看", v -> {
                    // 导航到统计数据界面
                    Navigation.findNavController(v).navigate(R.id.nav_stats);
                })
                .show();
    }
}
